Topological Cluster Statistics (TCS)¶


Notebook 12: Brain Visualizations, ground truth¶


This notebook contains scripts that generate brain visualizations of the putative ground truth effects.


Packages and basic functions¶


Loading required packages

In [1]:
import os
import numpy as np
import pandas as pd
import nibabel as nib
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import metrics
from tqdm.notebook import tqdm

from cerebro import cerebro_brain_utils as cbu
from cerebro import cerebro_brain_viewer as cbv

Basic functions

In [2]:
def ensure_dir(file_name):
    os.makedirs(os.path.dirname(file_name), exist_ok=True)
    return file_name


def write_np(np_obj, file_path):
    with open(file_path, 'wb') as outfile:
        np.save(outfile, np_obj)


def load_np(file_path):
    with open(file_path, 'rb') as infile:
        return np.load(infile)
In [3]:
def plot_cifti_with_cerebro(dscalar_data, axes, colormap=plt.cm.Spectral, clims=(-1,1),):
    my_brain_viewer = cbv.Cerebro_brain_viewer(offscreen=True, background_color=(1,1,1,0),)

    surface = 'inflated'
    surface_model = my_brain_viewer.load_template_GIFTI_cortical_surface_models(surface)

    cifti_space = my_brain_viewer.visualize_cifti_space(
        volumetric_structures='all',
        cifti_expansion_scale=20,
        cifti_left_right_seperation=10,
        volumetric_structure_offset=(0, 5, -40),
        volume_rendering='surface',
    )

    dscalar_layer = my_brain_viewer.add_cifti_dscalar_layer(
        dscalar_data=dscalar_data,
        colormap=colormap,
        clims=clims,
        opacity=0.8)

    ax = axes[0]
    ax.axis('off')
    view = ((-250, 200, 0), None, None, None)
    camconf = my_brain_viewer.view_to_camera_config(view)
    camconf = my_brain_viewer.zoom_camera_to_content(camconf)
    camconf['camera_pos'] = tuple([x * 0.7 for x in camconf['camera_pos']])
    my_brain_viewer.viewer.change_view(**camconf)
    my_brain_viewer.offscreen_draw_to_matplotlib_axes(ax)

    ax = axes[1]
    ax.axis('off')
    camconf = my_brain_viewer.view_to_camera_config("R")
    camconf = my_brain_viewer.zoom_camera_to_content(camconf)
    camconf['camera_pos'] = tuple([x * 0.7 for x in camconf['camera_pos']])
    my_brain_viewer.viewer.change_view(**camconf)
    my_brain_viewer.offscreen_draw_to_matplotlib_axes(ax)

    my_brain_viewer.viewer.window.destroy()
    
    plt.show()

Plot settings (latex is used for better plotting)

In [4]:
sns.set()
sns.set_style("darkgrid")

%matplotlib inline
%config InlineBackend.figure_format = 'retina'
In [5]:
plt.rc('text', usetex=True)
plt.rc('text.latex', preamble=r'\usepackage{mathtools} \usepackage{sfmath}')

plt.rc('xtick', labelsize=20)
plt.rc('ytick', labelsize=20)
plt.rc('axes', labelsize=24)

plt.rc('figure', dpi=500)

Loading the ground truth¶


The ground truth stored in notebook 2 is loaded here.

In [6]:
# list of all tasks and the cope number related to each selected contrast
tasks = {
    'EMOTION': '3',  # faces - shapes
    'GAMBLING': '6',  # reward - punish
    'RELATIONAL': '4',  # rel - match
    'SOCIAL': '6',  # tom - random
    'WM': '20',  # face - avg
}
In [7]:
# Compute mean and std, followed by a parametric z-score (one sample t-test)
ground_truth_effect = {}
# Base directory where files are stored at
base_dir='/data/netapp01/work/sina/structural_clustering/PALM_revision_1'

for task in tqdm(tasks, desc="Tasks loop", leave=True):
    ground_truth_effect[task] = load_np(
        '{}/ground_truth/cohen_d_{}_cope{}.dscalar.npy'.format(base_dir, task, tasks[task]),
    )
Tasks loop:   0%|          | 0/5 [00:00<?, ?it/s]

Visualizing brains¶


Cerebro brain viewer was used for brain visualizations.

In [8]:
mycm = matplotlib.colors.LinearSegmentedColormap.from_list(
    'my_gradient',
    (
        (0.0, (0.1, 0.1, 1.,)),
        (0.25, (0.1, 1., 1.,)),
        (0.5, (1., 1., 1.,)),
        (0.75, (1., 1., 0.1,)),
        (1.0, (1., 0.1, 0.1,)),
    )
)

fig, ax = plt.subplots(1, 1, figsize=(5, 1),)
ax.imshow(np.linspace(0, 1, 256)[np.newaxis, :].repeat(20,0), cmap=mycm)
ax.set_axis_off()
In [9]:
for task in tasks:
    print(task)
    
    fig, axes = plt.subplots(1, 2, figsize=(10, 8),)
    plt.subplots_adjust(wspace=0, hspace=0)
    plot_cifti_with_cerebro(ground_truth_effect[task], colormap=mycm, axes=axes)
EMOTION
GAMBLING
RELATIONAL
SOCIAL
WM
In [ ]: